<!--
 * @description  : 案件-行政处罚文书送达地址确认书
 * @descriptionDetail: 案件-行政处罚文书送达地址确认书
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-08-25 15:43:11
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :isWhite="false" backText="" title="文书信息">
      <view class="white-color" @click="printOrDown(state.canEdit)">
        {{ state.canEdit?'预览':'打印' }}
      </view>
    </theme-navbar>
    <!-- #endif -->
		<!-- #ifdef H5-WECHAT || H5-EMP -->
		<fab-button :content="state.canEdit?fContent:fContents" @fabtrigger="fabtrigger" />
		<!-- #endif -->
    <view class="main-content">
      <view class="main-title">
        行政处罚文书送达地址确认书
      </view>
      <u-form
        label-width="auto"
        label-position="left"
        class="form-content"
        :model="docIns"
        :error-type="['border-bottom','message',]"
        ref="uForm"
      >
        <u-form-item label="案件名称" label-position="top" :required="true" prop="caseName">
          <u-input
            type="text"
            :clearable="false"
            :disabled="!state.canEdit"
            placeholder="请输入"
            v-model="docIns.caseName"
          />
        </u-form-item>
        <view style="width: calc(100% + 30px);margin-left: -15px;">
          <form-section title="受送达人提供的送达地址及确认的送达方式"></form-section>
        </view>
        <u-form-item label="受送达人" :required="true" prop="serviceParty">
          <u-input
            placeholder="请输入"
            inputAlign="right"
            :disabled="!state.canEdit"
            v-model="docIns.serviceParty"
          />
        </u-form-item>
        <u-form-item label="证件类型" prop="serviceIdCardType">
          <dic-input
            :keyWord="$u.dic.DIC_KEYS.IDCARD_TYPE"
            :dicCode="docIns.serviceIdCardType"
            :border="false"
            type="select"
            inputAlign="right"
            :select-open="dicSelectOpen($u.dic.DIC_KEYS.IDCARD_TYPE)"
            placeholder="请选择"
            v-model="docIns.serviceIdCardTypeStr"
            @changeInputModelData="(name)=>{$set(docIns, 'serviceIdCardTypeStr', name)}"
            @click="showDic($u.dic.DIC_KEYS.IDCARD_TYPE,docIns.serviceIdCardType,'serviceIdCardType')"
          />
        </u-form-item>
        <u-form-item prop="serviceIdCard" label="证件号码">
          <u-input
            :disabled="!state.canEdit"
            placeholder="请输入证件号码"
            type="number"
            inputAlign="right"
            v-model="docIns.serviceIdCard"
          />
        </u-form-item>
        <u-form-item prop="serviceReceiver" label="收件人" :required="true">
          <u-input
            :disabled="!state.canEdit"
            placeholder="请输入收件人"
            type="text"
            inputAlign="right"
            v-model="docIns.serviceReceiver"
          />
        </u-form-item>
        <u-form-item label="固定电话">
          <u-input
            :disabled="!state.canEdit"
            placeholder="请输入固定号码"
            type="text"
            inputAlign="right"
            v-model="docIns.serviceFixPhone"
          />
        </u-form-item>
        <u-form-item label="手机号码" :required="true" prop="servicePhone">
          <u-input
            :disabled="!state.canEdit"
            placeholder="请输入手机号码"
            type="number"
            inputAlign="right"
            v-model="docIns.servicePhone"
          />
        </u-form-item>
        <u-form-item label="邮政编码" prop="servicePostcode">
          <u-input
            :disabled="!state.canEdit"
            placeholder="请输入邮政编码"
            type="number"
            inputAlign="right"
            v-model="docIns.servicePostcode"
          />
        </u-form-item>
        <u-form-item label="其他联系方式" label-position="top">
          <u-input
            :disabled="!state.canEdit"
            placeholder="请输入"
            type="textarea"
            v-model="docIns.serviceOtherContact"
          />
        </u-form-item>
        <u-form-item label="送达地址" :required="true" label-position="top" prop="serviceAddr">
          <u-input
            :disabled="!state.canEdit"
            placeholder="请输入"
            type="textarea"
            v-model="docIns.serviceAddr"
          />
        </u-form-item>
        <u-form-item label="是否同意电子送达">
          <view style="width: 100%;display: flex;flex-direction: row;justify-content: flex-end;">
            <u-switch
              active-value="1"
              inactive-value="0"
              :disabled="!state.canEdit"
              v-model="isEDelivery"
              @change="changeEDelivery"
            ></u-switch>
          </view>
        </u-form-item>
        <u-form-item label="电子送达类型" label-position="top" v-show="isEDelivery">
          <u-checkbox-group :wrap="true" width="100%" :disabled="!state.canEdit">
            <u-checkbox name="1" v-model="phoneChecked">
              <view class="flex-text-row check-list-item">
                <text class="u-m-r-30" style="width: 200rpx;">
                  手机
                </text>
                <u-input
                  type="number"
                  :disabled="!state.canEdit"
                  :border="true"
                  v-model="docIns.servicePhone"
                ></u-input>
              </view>
            </u-checkbox>
            <u-checkbox name="2" v-model="faxNoChecked">
              <view class="flex-text-row check-list-item">
                <text class="u-m-r-30" style="width: 200rpx;">
                  传真
                </text>
                <u-input type="number" :disabled="!state.canEdit" :border="true" v-model="docIns.faxNo">
                </u-input>
              </view>
            </u-checkbox>
            <u-checkbox name="3" v-model="emailChecked">
              <view class="flex-text-row check-list-item">
                <text class="u-m-r-30" style="width: 200rpx;">
                  电子邮件
                </text>
                <u-input type="text" :disabled="!state.canEdit" :border="true" v-model="docIns.email">
                </u-input>
              </view>
            </u-checkbox>
            <u-checkbox name="4" v-model="instantMessageChecked">
              <view class="flex-text-row check-list-item">
                <text class="u-m-r-30" style="width: 200rpx;">
                  即时通讯
                </text>
                <u-input
                  type="text"
                  :disabled="!state.canEdit"
                  :border="true"
                  v-model="docIns.instantMessage"
                ></u-input>
              </view>
            </u-checkbox>
          </u-checkbox-group>
        </u-form-item>
        <view style="width: calc(100% + 30px);margin-left: -15px;">
          <form-section title="委托代理人提供的送达地址"></form-section>
        </view>
        <u-form-item label="受送达人" prop="entrustParty">
          <u-input
            inputAlign="right"
            placeholder="请输入"
            :disabled="!state.canEdit"
            v-model="docIns.entrustParty"
          />
        </u-form-item>
        <u-form-item label="证件类型" :required="true" prop="entrustIdCardType">
          <dic-input
            :keyWord="$u.dic.DIC_KEYS.IDCARD_TYPE"
            :dicCode="docIns.entrustIdCardType"
            :border="false"
            type="select"
            inputAlign="right"
            :select-open="dicSelectOpen($u.dic.DIC_KEYS.IDCARD_TYPE)"
            placeholder="请选择"
            v-model="docIns.entrustIdCardTypeStr"
            @changeInputModelData="(name)=>{$set(docIns, 'entrustIdCardTypeStr', name)}"
            @click="showDic($u.dic.DIC_KEYS.IDCARD_TYPE,docIns.entrustIdCardType,'entrustIdCardType')"
          />
        </u-form-item>
        <u-form-item prop="entrustIdCard" label="证件号码">
          <u-input
            :disabled="!state.canEdit"
            placeholder="请输入证件号码"
            type="number"
            inputAlign="right"
            v-model="docIns.entrustIdCard"
          />
        </u-form-item>
        <u-form-item prop="entrustReceiver" label="收件人">
          <u-input
            :disabled="!state.canEdit"
            placeholder="请请输入收件人"
            type="text"
            inputAlign="right"
            v-model="docIns.entrustReceiver"
          />
        </u-form-item>
        <u-form-item label="代理人姓名">
          <u-input
            :disabled="!state.canEdit"
            placeholder="请输入代理人姓名"
            type="text"
            inputAlign="right"
            v-model="docIns.agentName"
          />
        </u-form-item>
        <u-form-item prop="agentIdCard" label="身份证号码">
          <u-input
            :disabled="!state.canEdit"
            placeholder="请输入身份证号码"
            type="number"
            inputAlign="right"
            v-model="docIns.agentIdCard"
          />
        </u-form-item>
        <u-form-item label="固定电话">
          <u-input
            :disabled="!state.canEdit"
            placeholder="请输入固定号码"
            type="text"
            inputAlign="right"
            v-model="docIns.entrustFixPhone"
          />
        </u-form-item>
        <u-form-item label="手机号码" prop="entrustPhone">
          <u-input
            :disabled="!state.canEdit"
            placeholder="请输入手机号码"
            type="number"
            inputAlign="right"
            v-model="docIns.entrustPhone"
          />
        </u-form-item>
        <u-form-item label="邮政编码" prop="entrustPostcode">
          <u-input
            :disabled="!state.canEdit"
            placeholder="请输入邮政编码"
            type="number"
            inputAlign="right"
            v-model="docIns.entrustPostcode"
          />
        </u-form-item>
        <u-form-item label="送达地址" label-position="top">
          <u-input
            :disabled="!state.canEdit"
            placeholder="请输入"
            type="textarea"
            v-model="docIns.entrustAddr"
          />
        </u-form-item>
        <u-form-item label-position="top" :required="true" label="执法人员签名" prop="undertakerUuids">
          <u-input
            :disabled="true"
            placeholder="请选择"
            type="select"
            v-model="docIns.undertaker"
            @click="underTaker"
          />
        </u-form-item>
        <u-form-item label-width="200" label="当事人签名" label-position="left" prop="fileId">
          <view
            style="display: flex;flex-direction: row;justify-content: flex-end;width: 100%;"
            @click="showSignView"
          >
            <m-upload
              :uploadParam="{'fiGroupCode':'zmglpt-regie-zj-images'}"
              maxCount="1"
              :file-list="signImgList"
              uploadText="未签名"
              :showDefView="false"
              :deletable="state.canEdit"
              width="300rpx"
              height="150rpx"
              index="signImgList"
              :disabled="true"
              imageMode="aspectFit"
              @on-list-change="changeUpload"
            >
            </m-upload>
          </view>
          <signature
            :mustHor="true"
            :visible="isShowSignView"
            :disabled="!state.canEdit"
            @close="isShowSignView = false"
            @save="saveSign"
          >
          </signature>
        </u-form-item>
      </u-form>
      <view class="bottom-btn-info" v-if="state.canEdit">
        <u-row gutter="50">
          <u-col span="6">
            <u-button plain type="primary" @click="saveOrSubmit('save')">
              保存
            </u-button>
          </u-col>
          <u-col span="6">
            <u-button type="primary" @click="saveOrSubmit('submit')">
              提交
            </u-button>
          </u-col>
        </u-row>
      </view>
    </view>
    <dic-choice
      :keyWord="dicKeyWords"
      :currentSelect="dicCurrentSelect"
      v-model="dicShow"
      @confirm="selectDicConfirm"
    ></dic-choice>
    <!-- 人员选择 -->
    <u-popup mode="bottom" height="80%" v-model="personSelectShow">
      <person-selection :params="psParam" @choose="handlerChoosePerson"></person-selection>
    </u-popup>
  </view>
</template>
<script>
	import caseCommon from "../caseCommonMixin.js";
	import officeService from "@/service/case/office.service.js";
	import FormSection from "@/components/form-section.vue";
	import DicChoice from "@/components/dic_choice.vue";
	import DicInput from "@/components/dic_input.vue";
	import PersonSelection from "@/pages/case/components/personSelection.vue";
	import zjCommonService from "@/service/common/common.service";
	import Signature from "@/components/signature";
	import mUpload from '@/components/m-upload.vue';
	import fabButton from '@/components/uni-fab.vue';

	export default {
		components: {
			FormSection,
			DicChoice,
			DicInput,
			PersonSelection,
			Signature,
			mUpload,
			fabButton
		},
		mixins: [caseCommon, ],
		data() {
			return {
				isEDelivery: false,
				personSelectShow: false,
				psParam: {},
				rules: {
					caseName: [{
						required: true,
						message: '请输入案件名称',
						trigger: ['change', 'blur', ],
					}, ],
					serviceParty: [{
						required: true,
						message: '请输入收件人姓名',
						trigger: ['change', 'blur', ],
					}, ],
					serviceReceiver: [{
						required: true,
						message: '请输入受送达人',
						trigger: ['change', 'blur', ],
					}, ],
					servicePhone: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur', ],
						},
						{
							validator: (rule, value, callback) => {
								return this.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							trigger: ['change', 'blur', ],
						},
					],
					serviceAddr: [{
						required: true,
						message: '请输入送达地址',
						trigger: ['change', 'blur', ],
					}, ],
				},
				doc: {},
				docIns: {}, // 表单数据
				phoneChecked: false,
				faxNoChecked: false,
				emailChecked: false,
				instantMessageChecked: false,
				dicShow: false, // dic_select 是否显示
				dicKeyWords: "", // dic 关键字
				dicCurrentSelect: "", // dic 当前选择项
				idCardFile: '', // 指定哪个证件类型
				isShowSignView: false,
				signImgList: [],
				btnType: "",
				fContent: [{
					iconPath: require('@/static/oview.png'),
					selectedIconPath: require('@/static/oview.png'),
					text: '预览',
					active: false,
				}],
				fContents: [{
					iconPath: require('@/static/dy.png'),
					selectedIconPath: require('@/static/dy.png'),
					text: '打印',
					active: false,
				}]
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad() {
			this.caseParam = this.getRouteParam();
		},
		mounted() {
			this.docStep((docInfo) => {
				this.doc = docInfo;
				this.setRightBtns();
			});
			this.initDocData();
		},
		methods: {
			// 设置右侧标题
			setRightBtns() {
				// #ifdef H5-DINGDING
				this.$deviceApi.setRight(this.state.canEdit ? '预览' : '打印', () => {
					this.printOrDown(this.state.canEdit);
					this.setRightBtns();
				}, true, true);
				// #endif
			},
			fabtrigger(btn) {
				if (btn.index == 0) {
					this.printOrDown(this.state.canEdit);
				}
			},
			changeEDelivery(value) {
				this.docIns.isEDelivery = value;
			},
			// 数据字典组件选择事件
			dicSelectOpen: function(keyWord) {
				if (this.dicKeyWords == keyWord && this.dicShow) {
					return true;
				}
				return false;
			},
			showDic: function(key, cur, fileName) {
				if (this.dicShow) return;
				this.dicKeyWords = key;
				this.dicCurrentSelect = cur;
				this.dicShow = true;
				this.idCardFile = fileName;
			},
			selectDicConfirm: function(e) {
				// 类型
				if (this.dicKeyWords == this.$u.dic.DIC_KEYS.IDCARD_TYPE) {
					this.docIns[this.idCardFile + 'Str'] = e[0].label;
					this.docIns[this.idCardFile] = e[0].extra.bcbCode;
				}
			},
			underTaker() {
				this.psParam = {
					min: 1,
					selectedPsrLst: [],
					caseUuid: this.caseParam.caseUuid,
				};
				this.personSelectShow = true;
			},
			handlerChoosePerson(e) {
				this.personSelectShow = false;
				let employeeList = [...e, ];
				let tIds = [];
				let tNames = [];
				employeeList.forEach(el => {
					tIds.push(el.personUuid);
					tNames.push(el.personName);
				});
				this.docIns.undertakerUuids = tIds.join(",");
				this.docIns.undertaker = tNames.join(",");
			},
			// 初始化文书信息
			initDocData() {
				officeService.docFields(this.caseParam.docUuid, true).then(docConfigs => {
					if (docConfigs.success) {
						// 获取勘验笔录信息参数
						let parms = {
							id: this.caseParam.id,
							docUuid: this.caseParam.docUuid,
							bizUuid: this.caseParam.bizUuid,
						}
						officeService.getDocServiceAddrConfirm(parms).then(res => {
							let [tiInfo, rs, ] = [{}, {}, ];
							if (res.success && res.data.length === 2) {
								tiInfo = res.data[0];
								rs = res.data[1];
								Object.keys(tiInfo).forEach(key => {
									rs[key] = tiInfo[key];
								});
							} else {
								rs = res.data[0];
							}
							this.objMerge(this.docIns, rs);
							if (this.docIns.isEDelivery == 1) {
								this.isEDelivery = true;
								this.phoneChecked = this.isCheckEDelivery(this.docIns.servicePhone);
								this.faxNoChecked = this.isCheckEDelivery(this.docIns.faxNo);
								this.emailChecked = this.isCheckEDelivery(this.docIns.email);
								this.instantMessageChecked = this.isCheckEDelivery(this.docIns
									.instantMessage);
							} else {
								this.isEDelivery = false;
							}
							if (!this.$u.test.isEmpty(this.docIns.fileId)) {
								this.signImgList = [{
									gfiId: this.docIns.fileId,
								}, ];
							}
						});
					} else {
						this.$u.toast(docConfigs.msg);
					}
				});
			},
			isCheckEDelivery(value) {
				return !value || value.indexOf("/") != -1 ? false : true;
			},
			// 打印/预览
			printOrDown(flag) {
				if (flag) {
					// 调接口预览
					this.saveOrSubmit('preview');
				} else {
					this.downloadFile(this.doc.pdfFileId);
				}
			},
			downloadFile(fileId, titleName, isDownload) {
				let pdfIds = fileId;
				if (!pdfIds) {
					this.$u.toast("没有文书");
					return;
				}
				this.setRouteParam({
					fileId: pdfIds,
					fileName: titleName,
					isDownload: isDownload,
				});
				this.$u.route('pages/commonPage/printerComponent');
			},
			saveSign(v) {
				console.log(v);
				this.isShowSignView = false;
				this.$modal.showLoading('保存签名...');
				let uploadParam = {
					'fiGroupCode': 'zmglpt-regie-zj-images',
				};
				uploadParam.fileName = Date.now() + '.jpg';
				zjCommonService.uploadBase64ForApp(v, uploadParam).then(res => {
					this.$modal.hideLoading();
					if (res.success) {
						this.signImgList = [res.bean, ]
						this.docIns.fileId = res.bean.gfiId;
					} else {
						console.log(res.msg);
						this.$u.toast('签名信息保存失败');
					}
				}).catch(er => {
					console.log(er);
					this.$modal.hideLoading();
					this.$u.toast('签名信息保存失败');
				});
			},
			// 上传/删除图片事件
			changeUpload(list, key) {
				if (key == 'signImgList') {
					if (list.length == 0) {
						this.docIns.fileId = "";
						this.signImgList = []
					}
					return;
				}
			},
			showSignView() {
				if (!this.state.canEdit) return;
				this.isShowSignView = true;
			},
			// 表单验证
			validForm(type) {
				let basicValid = false;
				this.btnType = type;
				this.$refs.uForm.validate(valid => {
					if (valid) {
						basicValid = true;
					} else {
						basicValid = false;
					}
				});
				return basicValid;
			},
			// 保存或提交
			saveOrSubmit(type) {
				let flag = this.validForm(type);
				if (flag) {
					this.handleOperBtn(type);
				}
			},
			handleOperBtn(flag) {
				let [docGoodsReg, self, ] = [this.docIns, this, ];
				let {
					docUuid,
					id,
					titemUuid,
					type,
					bizUuid,
					caseCode,
					caseType,
					gfaCode,
				} = this.caseParam;
				docGoodsReg.caseUuid = this.caseParam.caseUuid;
				// 是否同意电子送达
				docGoodsReg.isEDelivery = this.isEDelivery ? 1 : 0;
				this.$u.loading('数据保存中...');
				officeService.saveDocServiceAddrConfirm(docGoodsReg, docUuid, titemUuid, id, type).then((res) => {
					this.$u.hideLoading();
					if (res.success) {
						this.$u.toast(res.msg);
						let bean = res.bean;
						let saveData = res.data[0];
						this.docIns = {
							...this.docIns,
							...bean,
						};
						try {
							if (!this.doc) this.doc = res.data[0];
						} catch (e) {
							console.log(e);
						}
						if (flag === 'submit') {
							if (self.signImgList.length > 0) {
								this.$u.loading('数据提交中...');
								officeService.submitDocServiceAddrConfirm(this.docIns, docUuid, titemUuid, id, type)
									.then(res => {
										this.$u.hideLoading();
										this.saveBehaviorLog(1, this.caseParam, this.doc);
										if (res.success) {
											// 返回列表
											this.$u.toast(res.msg);
											self.backPrev({
												paramKey: "offiList",
												param: {
													caseUuid: bizUuid,
													caseCode: caseCode,
													caseType: caseType,
												},
											});
										} else {
											this.$u.toast(res.msg);
										}
									})
							} else {
								this.$modal.confirm('当事人未签名，是否继续提交?', () => {
									this.$u.loading('数据提交中...');
									officeService.submitDocServiceAddrConfirm(this.docIns, docUuid, titemUuid, id, type)
										.then(res => {
											this.$u.hideLoading();
											if (res.success) {
												// 返回列表
												this.$u.toast(res.msg);
												self.backPrev({
													paramKey: "offiList",
													param: {
														caseUuid: bizUuid,
														caseCode: caseCode,
														caseType: caseType,
													},
												});
											} else {
												this.$u.toast(res.msg);
											}
										})
								}, )
							}
						} else if (flag === 'preview') { // 预览saveData.docInsUuid
							officeService.buildLocalPunish("/survey/doc-service-addr-confirm", saveData.docInsUuid)
								.then(
									pdfId => {
										if (pdfId.success) {
											this.downloadFile(pdfId.bean, "预览", false);
										} else {
											this.$u.toast(pdfId.msg);
										}
									});
						} else {
							this.saveBehaviorLog(0, this.caseParam, this.doc);
						}
					} else {
						this.$u.toast(res.msg);
					}
				});
			},
		},
	}
</script>

<style lang="scss" scoped>
	@import "../case_common.scss";

	.doc-no {
		display: inline-block;
		height: 35px;
		width: 60px;
		text-align: center !important;
		flex: none;
	}

	.check-desc {
		display: flex;
		align-items: center;

		.dec-input {
			width: 25%;
		}
	}

	.check-list-item {
		align-items: center;
		width: 100%;
		margin: 5rpx 0rpx;
	}

	/deep/.u-checkbox__label {
		width: 100% !important;
	}
</style>
